const { login } = require('../controller/user')
const { SuccessModel, ErrnoModel } = require('../model/resModel')
const { setSession } = require('../db/redis')



const handleUserRouter = (req, res) => {

    const method = req.method

    //登录接口
    if (method === 'POST' && req.path === '/api/user/login') {
        const { username, password } = req.body
        // const { username, password } = req.query
        const result = login(username, password)
        return result.then(data => {
            if (data.username) {
                //设置session值
                req.session.username = data.username
                req.session.realname = data.realname
                console.log(req.session);

                //更新redis内的session数据
                setSession(req.sessionId, req.session)

                return new SuccessModel()
            }
            return new ErrnoModel('登录失败！')
        })
    }

    //登录验证的测试
    if (method === 'GET' && req.path === '/api/user/login-test') {
        if (req.session.username) {
            req.body.author = req.session.username
            return Promise.resolve(
                new SuccessModel({
                    session: req.session
                })
            )
        }
        return Promise.resolve(new ErrnoModel('未登录'))

    }

}
module.exports = handleUserRouter